<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      :status-icon="true"
      label-width="80px"
      class="demo-ruleForm"
    >
      <el-form-item
        label="名称"
        prop="name"
      >
        <el-input
          v-model.trim="form.name"
          autocomplete="off"
          clearable
        />
      </el-form-item>
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="close">
        取 消
      </el-button>
      <el-button
        type="primary"
        @click="save"
      >
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
export default {
  name: "TableEdit",
  props: ["fetchData"],
  data() {
    return {
      form: {
        name: "",
      },
      id: null,
      created: true,
      rules: {
        name: [
          { required: true, trigger: "blur", message: "请输入区名称" },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }          
        ],
      },
      title: "",
      dialogFormVisible: false,
    };
  },
  created() {},
  methods: {
    showEdit(row) {
      if (!row) {
        this.title = "区信息添加";
        this.created = true;
      } else {
        this.id = row.id;
        this.title = "区信息编辑";
        this.form = Object.assign({}, row);
        this.created = false;
      }
      this.dialogFormVisible = true;
    },
    close() {
      this.$refs["form"].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
    },
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.created) {
            this.create();
          } else {
            this.edit();
          }
        } else {
          return false;
        }
      });
    },
    async create() {
      const res = await this.$http.post(`/area`, this.form);
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$emit("fetchData");
        this.$refs["form"].resetFields();
        this.dialogFormVisible = false;
        this.form = this.$options.data().form;
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      const res = await this.$http.put(`/area/${this.id}`, this.form);
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$emit("fetchData");
        this.$refs["form"].resetFields();
        this.dialogFormVisible = false;
        this.form = this.$options.data().form;
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
  },
};
</script>

<style>
.el-input__validateIcon {
  color : green;
}
</style>